<template>
  <div>
    <NavBar>
      <template v-slot:default>用户注册</template>
    </NavBar>
    <van-image src="https://www.lmonkey.com/_nuxt/img/logo.2a324bb.png" width="250px" height="80px"
      style="margin-left:50px;margin-top: 80px"></van-image>
    <van-form @submit="onSubmit">
      <van-field v-model="name" name="用户名" label="用户名" placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"></van-field>
      <van-field v-model="password" name="密码" label="密码" placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"></van-field>
      <van-field v-model="password_confirmation" name="确认密码" label="确认密码" placeholder="请输入确认密码"
        :rules="[{ required: true, message: '请填写确认密码' }]"></van-field>
      <van-field v-model="email" name="电子邮箱" label="电子邮箱" placeholder="请输入你的电子邮箱"
        :rules="[{ required: true, message: '请填写正确的电子邮箱格式' }]"></van-field>
      <div style="color: #42b983;font-size: 14px;margin-left: 10px;margin-top: 10px"
        @click="$router.push({ path: '/login' })">已有账号,立即登录</div>
      <van-button type="primary" style="width:200px;margin-left: 90px;margin-top: 20px" round
        native-type="submit">提交</van-button>
    </van-form>
  </div>
</template>

<script>
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { Notify, Toast } from "vant";
import { useRouter } from 'vue-router'
export default {
  name: "register",
  setup() {
    const router = useRouter()
    const form = reactive({
      name: '',
      password: '',
      password_confirmation: '',
      email: ''
    })
    const { proxy } = getCurrentInstance()
    const onSubmit = () => {
      if (form.password == form.password_confirmation) {
        proxy.$API.user.register(form).then(res => {
          if (res.status == 201) {
            form.password = ''
            form.password_confirmation = ''
            Toast.success('注册成功')
            setTimeout(() => {
              router.push({
                path: '/login'
              }, 1000)
            })
          }
        })
      } else {
        Notify('两次密码不一致')
      }
    }
    return {
      onSubmit,
      ...toRefs(form)
    }
  }
}
</script>

<style scoped>
::v-deep .van-field {
  padding: 16px;
}
</style>
